package org.wdcode.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.wdcode.common.tools.Conversion;
import org.wdcode.common.util.CommonUtil;

/**
 * 主要用来处理Request请求的中文编码格转化<br/>
 * <h2>注: encoding 编码格式 format是否格式化编码</h2>
 * @author WD
 * @since JDK6
 * @version 1.0 2009-03-01
 */
public final class EncodingFilter implements Filter {
	// 编码格式
	private String	encoding;

	/**
	 * 载入过滤器到服务 读取过滤器配置参数
	 * @param filterConfig 过滤器配置
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		// 设置编码
		encoding = Conversion.toString(filterConfig.getInitParameter("encoding"));
	}

	/**
	 * 过滤方法
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 编码生效并且request提交有格式
		if (!CommonUtil.isEmpty(encoding)) {
			// 编码值不为空
			request.setCharacterEncoding(encoding);
		}
		// 交出控制权
		chain.doFilter(request, response);
	}

	/**
	 * 销毁实例调用
	 */
	public void destroy() {
		encoding = null;
	}
}
